<template>
  <div class="login-container">
    <el-card class="login-box">
      <h1 class="login-title">登录</h1>
      <el-form :model="loginForm" @submit.prevent="login">
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              prefix-icon="User"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit" class="login-button">
            登录
          </el-button>
        </el-form-item>
      </el-form>
      <p class="register-link">
        没有账号？<router-link to="/register">立即注册</router-link>
      </p>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
      },
    };
  },
  methods: {
    async login() {
      try {
        const response = await axios.post(
            'http://localhost:8080/api/users/login',
            {
              username: this.loginForm.username,
              password: this.loginForm.password,
            },
            {
              headers: {
                'Content-Type': 'application/json', // 设置请求头为 JSON
              },
            }
        );

        if (response.data.message === 'Login successful') {
          const token = response.data.token; // 获取返回的 Token
          localStorage.setItem('token', token); // 存储 Token
          ElMessage.success('登录成功');
          this.$router.push('/data'); // 跳转到数据展示页
        } else {
          ElMessage.error('登录失败，请检查用户名和密码');
        }
      } catch (error) {
        ElMessage.error('登录失败，请检查用户名和密码');
      }
    },
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #6a11cb, #2575fc);
  background-size: cover; /* 背景铺满 */
  margin: 0; /* 去除默认边距 */
  padding: 0; /* 去除默认内边距 */
  width: 100vw; /* 确保宽度铺满屏幕 */
}

.login-box {
  width: 400px;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  color: #303133;
}

.login-button {
  width: 100%;
  margin-top: 10px;
}

.register-link {
  text-align: center;
  margin-top: 15px;
  font-size: 14px;
  color: #606266;
}

.register-link a {
  color: #409eff;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}
</style>